package cs6238.common.message.response;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import cs6238.common.ByteArray;
import cs6238.common.message.MessageId;

public class ListHostsResponse extends Response {

	private List<String> _hosts;
	
	public ListHostsResponse(){
		_hosts = new ArrayList<String>();
	}
	
	public void setHosts(List<String> hosts){
		_hosts = hosts;
	}
	
	public List<String> getHosts(){
		return _hosts;
	}
	
	@Override
	public byte[] serialize() {
		List<byte[]> byteList = new ArrayList<byte[]>();
		
		int total = 0;
		
		for(String host : _hosts){
			byte[] temp = ByteArray.writeString(host);
			total += temp.length;
			byteList.add(temp);
		}
		
		ByteBuffer bb = ByteBuffer.allocate(4 + 4 + total);
		bb.putInt(MessageId.LIST_HOSTS_RESPONSE.ordinal());
		bb.putInt(byteList.size());
		
		for(byte[] temp : byteList){
			bb.put(temp);
		}
		
		return bb.array();
	}

	@Override
	public void deserialize(byte[] buffer) {
		ByteBuffer bb = ByteBuffer.wrap(buffer);
		bb.getInt();
		int numStrings = bb.getInt();
		
		for(int i=0; i<numStrings; i++){
			_hosts.add(ByteArray.readString(bb));
		}
	}

}
